package cn.iocoder.yudao.module.pplan.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.distm.dal.dataobject.schedule.ScheduleRecordDO;
import cn.iocoder.yudao.module.distm.dal.dataobject.schedule.ScheduleRecordHistoryDO;
import cn.iocoder.yudao.module.distm.dal.mysql.schedule.ScheduleRecordHistoryMapper;
import cn.iocoder.yudao.module.distm.dal.mysql.schedule.ScheduleRecordMapper;
import cn.iocoder.yudao.module.distm.service.schedule.ScheduleRecordService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SyncDistmSchedeuleJob implements JobHandler {

    @Resource
    private ScheduleRecordMapper scheduleRecordMapper;

    @Resource
    private ScheduleRecordHistoryMapper scheduleRecordHistoryMapper;

    @Resource
    private ScheduleRecordService scheduleRecordService;

    @Override
    @TenantIgnore // 忽略多租户
    public String execute(String param) {

        // 查询调度数据--此处目前考虑数据量比较少，未考虑分页
        List<ScheduleRecordDO> scheduleRecordDOS = scheduleRecordMapper.selectList();
        if(CollectionUtil.isNotEmpty(scheduleRecordDOS)){
            List<Long> ids = scheduleRecordDOS.stream().map(ScheduleRecordDO::getId).collect(Collectors.toList());
            // 插入历史表
            List<ScheduleRecordHistoryDO> historyDOS = BeanUtils.toBean(scheduleRecordDOS, ScheduleRecordHistoryDO.class,
                    respVO -> {respVO.setOrgId(respVO.getId());respVO.setId(null);});
            scheduleRecordHistoryMapper.insertBatch(historyDOS);
            // 删除调度数据
            scheduleRecordMapper.deleteByIds(ids);
        }
        // 同步调度数据
        scheduleRecordService.syncQuarterPlan();
        return "同步调度数据成功";
    }

}
